package cn.manager.travel.web.servlet;

import cn.manager.travel.domain.Admin;
import cn.manager.travel.domain.New;
import cn.manager.travel.service.AdminService;
import cn.manager.travel.service.impl.AdminServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@WebServlet("/admin/*")
public class AdminServlet extends BaseServlet {
	
	private AdminService service = new AdminServiceImpl();
	
	public void getNews(HttpServletRequest request, HttpServletResponse response) throws Exception {
		List<New> news = service.showNews();
		json(response,news);
		
	}
	
	public void add(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String title = request.getParameter("title");
		String author = request.getParameter("author");
		String text = request.getParameter("text");
		
		service.add(title,author,text);
		response.sendRedirect(request.getContextPath()+"/admin.jsp");
	}
	
	public void upd(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String nID = request.getParameter("nID");
		String title = request.getParameter("title");
		String author = request.getParameter("author");
		String text = request.getParameter("text");
		service.upd(nID,title,author,text);
		response.sendRedirect(request.getContextPath()+"/admin.jsp");
	}
	
	public void del(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String nId = request.getParameter("nId");
		
		service.del(nId);
		response.sendRedirect(request.getContextPath()+"/admin.jsp");
	}
	
	public void quit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.getSession().removeAttribute("user");
		response.sendRedirect(request.getContextPath()+"/login.jsp");
	}
	
	public void login(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		Admin admin = service.login(username,password);
		if (admin == null){
			request.getSession().setAttribute("error","用户名或密码错误");
			response.sendRedirect(request.getContextPath() + "/login.jsp");
			
		}else {
			request.getSession().setAttribute("user", admin);
			response.sendRedirect(request.getContextPath() + "/admin.jsp");
		}
	}
}
